﻿using System.Collections.Generic;
using System.Linq;
using Demo.Identity.Permissions.Dto;

namespace Demo.Identity.Permissions;

/// <summary>
/// 权限建树帮助类
/// </summary>
public static class PermissionTreeBuilder
{
    /// <summary>
    /// 建立树形结构
    /// </summary>
    /// <param name="lst"></param>
    /// <returns></returns>
    public static List<PermissionTreeDto> Build(List<PermissionTreeDto> lst)
    {
        var result = lst.ToList();

        for (var i = 0; i < result.Count; i++)
        {
            if (result[i].ParentCode == null)
            {
                continue;
            }
            foreach (var item in lst)
            {
                item.Children ??= new List<PermissionTreeDto>();
                if (item.Code != result[i].ParentCode)
                {
                    continue;
                }

                item.Children.Add(result[i]);
                result.RemoveAt(i);
                i--;
                break;
            }
        }
        return result;
    }
}